<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" :label-col="labelCol" :wrapper-col="wrapperCol" labelAlign="left">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="模糊搜索">
                <a-input  placeholder="" v-model="search"/>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24">
                <a-button type="primary" @click="searchclick">查询</a-button>
            </a-col>
          </a-row>
          <a-row style="margin-top: 20px;margin-bottom: 20px;">
            <a-button type="primary" @click="addnew()">新建策略</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="modifypolicy()">修改策略</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="deletpolicy()">删除策略</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setobject()">指定策略对象</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setexcutetime()">指定策略执行时间</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setOnOff()">开启/关闭策略</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="getlog()">查看日志</a-button>
          </a-row>
        </a-form>
      </div>

      <a-row>
        <a-table :columns="columns" :data-source="data" :row-selection="rowSelection" :pagination="tablepagination"  @change="tablechange">
          <template slot="priorityLevel" slot-scope="text, record">
            {{PriorityMap[text]}}
          </template>
          <template slot="type" slot-scope="text, record">
            {{PolicyTypeMap[text]}}
          </template>
          <template slot="status" slot-scope="text, record">
            <a-tag v-if="text == 0" color="red">{{OnOffMap[text]}}</a-tag>
            <a-tag v-if="text == 1" color="green">{{OnOffMap[text]}}</a-tag>
          </template>
          <template slot="executionTime" slot-scope="text, record">
            {{WeekMap[JSON.parse(text).week]}} {{JSON.parse(text).time}}
          </template>
          <template slot="executionStatus" slot-scope="text, record">
            <template v-if="text == 2 ">已完成</template>
            <template v-if="text == 0 "><span style="color: red">未执行</span></template>
            <template v-if="text == 1"><span style="color: #00CC00">进行中</span></template>
          </template>
          <template slot="createTime" slot-scope="text, record">
            {{text.replace('T',' ')}}
          </template>
          <template slot="inventoryGroupId" slot-scope="text, record">
            {{text?assetsmap[text].title:''}}
          </template>
        </a-table>
      </a-row>
    </a-card>

    <Mymodal ref="mymodal"></Mymodal>
    <Detailmodal ref="detailmodal"></Detailmodal>
  </page-header-wrapper>
</template>

<script>
import Mymodal from '@/components/mycomp/mymodal.vue'
import Detailmodal from '@/components/mycomp/detailmodal'
import {PolicyType,DangerLevel,Priority,RestartType,OnOff,PriorityMap,PolicyTypeMap,OnOffMap,WeekMap} from '../../utils/constant'
import {getpatchgrouplist} from '@/api/patch'
import { addpolicy, getPolicyList, deletepolicy, updateExtime, updateonoff, excuteStrategy } from '@/api/policy'
import {getPolicyLog} from '@/api/log'
import { getDepartmentList } from '@/api/department'
export default {
  name: "test",
  components: { Mymodal,Detailmodal },
  data(){
    return{
      PolicyType,
      DangerLevel,
      Priority,
      PriorityMap,
      PolicyTypeMap,
      OnOffMap,
      WeekMap,
      RestartType,
      OnOff,
      search:'',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      rowSelection:{
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectarray = selectedRows
          document.getElementById('app').style.transform = `scale(1)`
          document.getElementById('app').style.transformOrigin = `0 0`
          document.getElementById('app').style.height = `100%`
          setTimeout(()=>{
            var scale = (window.innerWidth-20)/1900
            document.getElementById('app').style.transform = `scale(${scale})`
            document.getElementById('app').style.transformOrigin = `0 0`
            document.getElementById('app').style.height = `${100/scale}%`
          },0)
        },
        onSelect: (record, selected, selectedRows) => {
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
        },
      },
      tablepagination:{
        showTotal:(total, range) => {return `共搜索到${total}条数据`},
        current:1,
        total:0
      },
      columns:[
        {
          title:'策略名称',
          dataIndex: 'strategyName',
          key: 'strategyName',
        },
        {
          title:'策略优先级',
          dataIndex: 'priorityLevel',
          key: 'priorityLevel',
          scopedSlots: { customRender: 'priorityLevel' },
        },
        {
          title:'策略类型',
          dataIndex: 'type',
          key: 'type',
          scopedSlots: { customRender: 'type' },
        },
        {
          title:'策略状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title:'策略执行对象',
          dataIndex: 'inventoryGroupId',
          key: 'inventoryGroupId',
          scopedSlots: { customRender: 'inventoryGroupId' },
        },
        {
          title:'策略执行时间',
          dataIndex: 'executionTime',
          key: 'executionTime',
          scopedSlots: { customRender: 'executionTime' },
        },
        {
          title:'策略有效时段',
          dataIndex: 'effectiveTime',
          key: 'effectiveTime',
        },
        {
          title:'当前任务执行度',
          dataIndex: 'executionStatus',
          key:'executionStatus',
          scopedSlots: { customRender: 'executionStatus' },
        },
        {
          title:'策略建立时间',
          dataIndex: 'createTime',
          key:'createTime',
          scopedSlots: { customRender: 'createTime' },
        }
      ],
      selectarray:[],
      data:[],
      treedata:[],
      assetsgroup:[],
      assetsmap:{}
    }
  },
  mounted() {
    this.loadpatchgroup()
    this.getassets().then(()=>{
      this.getlist()
    })
  },
  methods:{
    searchclick(){
      this.tablepagination.current = 1
      this.getlist()
    },
    setassetsok(params){
      excuteStrategy(params).then(res=>{
        this.$message.success('操作成功')
        this.getlist()
      })
    },
    getallnode(list){
      let array = []
      for(let i =0;i<list.length;i++){
        array.push(list[i])
        if(list[i].children){
          array = array.concat(this.getallnode(list[i].children))
        }
      }
      return array
    },
    getassets(){
      return getDepartmentList({isHaveWhole:0}).then(res=>{
        if(res.data){
          this.assetsgroup = this.transtotree(res.data)

          let list = this.getallnode(this.assetsgroup)
          for(let i in list){
            this.assetsmap[list[i].key] = list[i]
          }
        }
      })
    },
    setobject(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      let id = this.getids()
      let modalinfo = {
        title:'指定策略对象',
        list:[
          {name:'inventoryGroupId',label:'资产组',require:true,type:'tree',errortip:'请选择资产组',treedata:this.assetsgroup},
        ],
        ok:this.setassetsok.bind(this),
        moreinfo:{
          strategyId:id
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },
    tablechange(pagination){
      this.tablepagination = pagination
      this.getlist()
    },
    loadpatchgroup(){
      getpatchgrouplist({a:1}).then(res=>{
        this.groupMap = {}
        if(res.data){
          this.treedata = this.transtotree(res.data)[0].children
        }
      })
    },
    addnew(){
      let modalinfo = {
        title:'新建策略',
        list:[
          {name:'strategyName',label:'策略名称',require:true,type:'input',errortip:'请输入名称'},
          {name:'type',label:'策略类型',require:true,type:'radio',errortip:'请选择策略类型',radiodata:this.PolicyType,tip:'循环策略根据策略触发时间重复执行，一次性策略按照触发时间执行一次后自动关闭'},
          {name:'executionTime',label:'触发时间',require:true,type:'weektime',errortip:'请输入触发时间'},
          {name:'effectiveTime',disable:'true',label:'有效时段',type:'timerank',checkname:'triggerSwitich',checklabel:'仅触发日有效',},
          {name:'riskLevel',label:'补丁风险级别',type:'radio',require:true,errortip:'请选择补丁风险级别',radiodata:this.DangerLevel},
          {name:'patchGroupId',label:'选择补丁组',require:true,type:'tree',errortip:'请选择补丁组',treedata:this.treedata},
          {name:'priorityLevel',label:'优先级设置',type:'select',require:true,errortip:'请选择优先级',selectdata:this.Priority},
          // {name:'inventoryReceiveTips',label:'资产接收补丁提示',type:'input',checkname:'inventoryReceiveSwitch',checklabel:'提示',},
          {name:'systemRestartSwitch',disable:'true',label:'系统重启设置',type:'select',selectdata:this.RestartType},
          {name:'rollbackSwitch',disable:'true',label:'开启回滚模式',type:'radio',radiodata:this.OnOff,tip:'开启回滚模式，需保证Linux系统盘btrfs，建议系统盘和数据盘分开'},
          {name:'pushFailed',disable:'true',label:'推送失败处置方式',type:'pushmethod'},
        ],
        ok:this.createokfun.bind(this),
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },

    modifypolicy(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      if(this.selectarray && this.selectarray.length >1){
        this.$message.info('此操作只支持一条数据')
        return
      }

      let item = this.selectarray[0]

      let modalinfo = {
        title:'修改策略',
        list:[
          {name:'strategyName',label:'策略名称',require:true,type:'input',errortip:'请输入名称',value:item.strategyName},
          {name:'type',value:item.type.toString(),label:'策略类型',require:true,type:'radio',errortip:'请选择策略类型',radiodata:this.PolicyType,tip:'循环策略根据策略触发时间重复执行，一次性策略按照触发时间执行一次后自动关闭'},
          {name:'executionTime',value:item.executionTime,label:'触发时间',require:true,type:'weektime',errortip:'请输入触发时间'},
          {name:'effectiveTime',disable:'true',value:item.effectiveTime,checkvalue:item.triggerSwitich,label:'有效时段',type:'timerank',checkname:'triggerSwitich',checklabel:'仅触发日有效',},
          {name:'riskLevel',value:item.riskLevel.toString(),label:'补丁风险级别',type:'radio',require:true,errortip:'请选择补丁风险级别',radiodata:this.DangerLevel},
          {name:'patchGroupId',value:item.patchGroupId,label:'选择补丁组',require:true,type:'tree',errortip:'请选择补丁组',treedata:this.treedata},
          {name:'priorityLevel',value:item.priorityLevel.toString(),label:'优先级设置',type:'select',require:true,errortip:'请选择优先级',selectdata:this.Priority},
          // {name:'inventoryReceiveTips',value:item.inventoryReceiveTips,checkvalue:item.inventoryReceiveSwitch,label:'资产接收补丁提示',type:'input',checkname:'inventoryReceiveSwitch',checklabel:'提示',},
          {name:'systemRestartSwitch',disable:'true',value:item.systemRestartSwitch.toString(),label:'系统重启设置',type:'select',selectdata:this.RestartType},
          {name:'rollbackSwitch',disable:'true',value:item.rollbackSwitch.toString(),label:'开启回滚模式',type:'radio',radiodata:this.OnOff,tip:'开启回滚模式，需保证Linux系统盘btrfs，建议系统盘和数据盘分开'},
          {name:'pushFailed',disable:'true',value:item.pushFailed,label:'推送失败处置方式',type:'pushmethod'},
        ],
        ok:this.createokfun.bind(this),
        moreinfo:{
          id:item.id
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)

    },


    createokfun(params){
      let t = JSON.parse(params.executionTime)
      if(params.type != '2'){
        t.mode = 1
        t.time = t.date.split('T')[0] + ' ' + (t.time.indexOf(' ')>0?t.time.split(' ')[1]:t.time)
      }else{
        t.mode = 2
      }
      params.executionTime = JSON.stringify(t)

      params.patchDistributeType = 1
      if(params.inventoryReceiveSwitch){
        params.inventoryReceiveSwitch = params.inventoryReceiveSwitch[0]?1:0
      }
      if(params.triggerSwitich){
        params.triggerSwitich = params.triggerSwitich[0]?1:0
      }
      addpolicy(params).then(res=>{
        this.$message.success('操作成功')
        this.getlist()
      })
    },


    deletpolicy(){

      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      let id = this.getids()

      this.$confirm({
        title: '是否确认删除数据?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk:()=> {
          deletepolicy({id:id}).then(res=>{
            this.$message.success('操作成功')
            this.getlist()
          })
        }
      });
    },

    setexcutetime(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      let id = this.getids()

      let modalinfo = {
        title:'指定策略执行时间',
        list:[
          {name:'executionTime',label:'执行时间',require:true,type:'weektime',errortip:'请输入执行时间'},
        ],
        ok:this.updateextime.bind(this),
        moreinfo:{
          ids:id
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },
    updateextime(params){
      updateExtime(params).then(res=>{
        this.$message.success('操作成功')
        this.getlist()
      })
    },
    updateonoff(params){
      updateonoff(params).then(res=>{
        this.$message.success('执行成功，请等待几分钟')
        this.getlist()
      })
    },
    setOnOff(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      let id = this.getids()

      let modalinfo = {
        title:'开启/关闭策略',
        list:[
          {name:'status',label:'策略设置',require:true,type:'select',errortip:'请选择',selectdata:this.OnOff},
        ],
        ok:this.updateonoff.bind(this),
        moreinfo:{
          ids:id
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },

    getids(){
      let arry = []
      for(let i in this.selectarray){
        arry.push(this.selectarray[i].id)
      }
      let id = arry.join(',')
      return id
    },
    getlist(){
      let params = {}
      params.pageNo = this.tablepagination.current
      params.pageSize = 10
      params.search = this.search
      params.patchDistributeType = 1
      getPolicyList(params).then(res=>{
        let record = res.data.records
        for(let i in record){
          record[i].key =record[i].id
        }
        this.data = record
        this.tablepagination.total = res.data.total
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    transtotree(list){
      let arry = []
      for(let i in list){
        let json = {}
        json.title = list[i].name
        json.key = list[i].id
        json.value = list[i].id
        json.pid = list[i].pId
        if(list[i].childNode){
          json.children = this.transtotree(list[i].childNode)
        }
        arry.push(json)
      }
      return arry
    },
    getlog(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      if(this.selectarray && this.selectarray.length >1){
        this.$message.info('此操作只支持一条数据')
        return
      }

      let item = this.selectarray[0]

      let modalinfo = {
        title:'日志详情',
        type:'table',
        query:getPolicyLog,
        params:{search:item.strategyName},
        width:1000,
        list:[
          {label:'策略名称',value:'strategy_name'},
          {label:'软件包名称',value:'name'},
          {label:'执行时间',value:'time'},
          {label:'执行失败资产数',value:'counts_fail'},
          {label:'执行成功资产数',value:'counts_success'},
          {label:'不可达资产数',value:'counts_unreachable'},
          {label:'失败详情',value:'failed'},
          {label:'不可达详情',value:'unreachable'},
        ],
      }
      this.$refs.detailmodal.showmodal(modalinfo)
    }
  }
}
</script>

<style scoped>

</style>